﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SmartSpace.Core;
using System.Configuration;
using SmartSapce.ServiceLocation;
using SmartSpace.Web;

namespace SmartSpace.WebApp
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(User.Identity.Name))
            {
                ICoreService service = ServiceLocator.Get<ICoreService>();
                User user = service.GetUser(User.Identity.Name);
                if (user != null)
                {
                    System.Web.Security.FormsAuthentication.SetAuthCookie(user.Account, true);
                    Response.Redirect(System.Web.Security.FormsAuthentication.DefaultUrl);
                }

                //ICoreService service = ServiceLocator.Get<ICoreService>();

                //if (User.Identity.IsAuthenticated && service.GetUser(User.Identity.Name) != null)
                //{
                //    Response.Redirect(System.Web.Security.FormsAuthentication.DefaultUrl);
                //}
                //else
                //{
                //    System.Web.Security.FormsAuthentication.SignOut();
                //}
            }
            else if (SsSite.Current != null && SsSite.Current.IsAllowAnonymous && SsSite.Current.AnonymousUserId != null)
            {
                ICoreService service = ServiceLocator.Get<ICoreService>();
                User anonymousUser = service.GetUser(SsSite.Current.AnonymousUserId.Value);
                if (anonymousUser != null)
                {
                    System.Web.Security.FormsAuthentication.SetAuthCookie(anonymousUser.Account, true);
                    Response.Redirect(System.Web.Security.FormsAuthentication.DefaultUrl);
                }
            }
            else
            {
                Label1.Text = User.Identity.Name;
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            ICoreService service = ServiceLocator.Get<ICoreService>();

            if (service.GetUser(TextBox1.Text) != null)
            {
                System.Web.Security.FormsAuthentication.SetAuthCookie(TextBox1.Text, true);
                Response.Redirect(System.Web.Security.FormsAuthentication.DefaultUrl);
            }
        }
    }
}